/**
 * 变量
 */

import { Mark, Plugin } from 'tiptap'
import { updateMark, removeMark, pasteRule } from 'tiptap-commands'
import { getMarkAttrs } from 'tiptap-utils'

export default class Vars extends Mark {

  get name() {
    return 'vars'
  }

  get defaultOptions() {
    return {
      openOnClick: true,
    }
  }

  get schema() {
    return {
      attrs: {
        code: {
          default: null,
        },
      },
      inclusive: false,
      parseDOM: [
        {
          tag: 'var[code]',
          getAttrs: dom => ({
            code: dom.getAttribute('code'), // 
          }),
        },
      ],
      toDOM: node => ['var', {
        // ...node.attrs,
        code: node.attrs.code,
      }, 0],
    }
  }

  commands({ type }) {
    return attrs => {
      // console.log('xxx: '+Math.random(),attrs)
      if (attrs.code) {
        return updateMark(type, attrs)
      }

      return removeMark(type)
    }
  }

  pasteRules({ type }) {
    console.log('-----------------pasteRules')
    return [
      pasteRule(
        /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-zA-Z]{2,}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)/g,
        type,
        code => ({ code: code }),
      ),
    ]
  }

  get plugins() {
    if (!this.options.openOnClick) {
      return []
    }

    return [
      new Plugin({
        props: {
          // handleClick: (view, pos, event) => {
          //   const { schema } = view.state
          //   const attrs = getMarkAttrs(view.state, schema.marks.vars)
          //   console.log('handleClick。。。。')
          //   if (attrs.href && event.target instanceof HTMLAnchorElement) {
          //     event.stopPropagation()
          //     window.open(attrs.href)
          //   }
          // },
        },
      }),
    ]
  }

}